<template>
    <a-button type="primary" @click="showModal">Open Modal</a-button>
    <a-modal
      ref="modalRef"
      v-model:visible="visible"
      :wrap-style="{ overflow: 'hidden' }"
      @ok="handleOk"
    >
      <p>Some contents...</p>
      <p>Some contents...</p>
      <p>Some contents...</p>

      <template #title>
          <div ref="modalTitleRef" style="width: 100%; cursor: move">Draggable Modal</div>
      </template>

      <template #modalRender="{ originVNode }">
        <div :style="transformStyle">
          <component :is="originVNode" />
        </div>
      </template>
    </a-modal>

</template>
<script lang="ts" setup>
  import { userModalDrag } from './useModalDrag';
  import { watch, CSSProperties, watchEffect, ref, toRef } from 'vue';
  import { useDraggable } from '@vueuse/core';

  let visible = $ref<boolean>(false);

  const showModal = () => {
    visible = true;
  };

  const handleOk = (e: MouseEvent) => {
    console.log(e);
    visible = false;
  };


 const { transformStyle } = userModalDrag();



  // const modalTitleRef = ref<HTMLElement>(null);
  // const { x, y, isDragging } = useDraggable(modalTitleRef);

  // let startX = $ref<number>(0);
  // let startY = $ref<number>(0);
  // let startedDrag = $ref(false);
  // let transformX = $ref(0);
  // let transformY = $ref(0);
  // let preTransformX = $ref(0);
  // let preTransformY = $ref(0);
  // let dragRect = $ref({ left: 0, right: 0, top: 0, bottom: 0 });

  // watch([x, y], () => {
  //   if (!startedDrag) {
  //     startX = x.value;
  //     startY = y.value;
  //     const bodyRect = document.body.getBoundingClientRect();
  //     const titleRect = modalTitleRef.value.getBoundingClientRect();
  //     dragRect.right = bodyRect.width - titleRect.width;
  //     dragRect.bottom = bodyRect.height - titleRect.height;
  //     preTransformX = transformX;
  //     preTransformY = transformY;
  //   }
  //   startedDrag = true;
  // });

  // watch(isDragging, () => {
  //   if (!isDragging) {
  //     startedDrag = false;
  //   }
  // });

  // watchEffect(() => {
  //   if (startedDrag) {
  //     transformX =
  //       preTransformX +
  //       Math.min(Math.max(dragRect.left, x.value), dragRect.right) -
  //       startX;
  //     transformY =
  //       preTransformY +
  //       Math.min(Math.max(dragRect.top, y.value), dragRect.bottom) -
  //       startY;
  //   }
  // });

  // const transformStyle = $computed<CSSProperties>(() => {
  //   return {
  //     transform: `translate(${transformX}px, ${transformY}px)`,
  //   };
  // });

</script>
